<template>
	<view class="content">
		<Header @open="open"></Header>
		<div class="panel" :style="'height:calc(100vh - '+(menuClint.top + menuClint.height +10)+'px)'">
			<div class="primary_con" v-if="messages.length <= 0">
				<div class="">
					<uni-icons type="chatboxes" color="#303030" size="30"></uni-icons>
					<h3>AI能力</h3>
					<p @click="assign('scene是什么意思')">scene是什么意思</p>
					<p @click="assign('莲藕排骨汤怎么做')">莲藕排骨汤怎么做</p>
					<p @click="assign('今天的世界有哪些新闻热点')">今天的新闻热点</p>
					<p @click="assign('查询xx星座运势')">查询星座运势</p>
					<p @click="assign('有趣的科学实验')">有趣的科学实验</p>
					<p @click="assign('全球高分电影推荐')">全球高分电影推荐</p>
					<p>
						<uni-icons type="more-filled" color="#545454" size="22"></uni-icons>
					</p>
				</div>
				<div class="">
					<uni-icons type="map" color="#303030" size="30"></uni-icons>
					<h3>AI办公</h3>
					<p @click="assign('文章润色')">文章润色</p>
					<p @click="assign('写一篇方案报告')">写一篇方案报告</p>
					<p @click="assign('生成一篇关于xx的日报/周报')">生成一篇日报/周报</p>
					<p @click="assign('撰写一篇邮件/演讲稿')">撰写一篇邮件/演讲稿</p>
					<p @click="assign('代码报错解决')">代码报错解决</p>
					<p>
						<uni-icons type="more-filled" color="#545454" size="22"></uni-icons>
					</p>
				</div>
			</div>
			<div class="tip" v-if="messages.length <= 0">更多AI能力等你来探索！</div>
			<scroll-view class="con" scroll-y scroll-with-animation="true" id="chat_list" :scroll-top='scrollTop'>
				<contentList :contentList="messages"></contentList>
			</scroll-view>
		</div>
		<div class="footer" :style="'bottom:'+inputBottom+'px'">
			<div class="input_con">
				<input :disabled="disabled" @focus="focusTextarea" @blur="blurTextarea" :adjust-position="false"
					type="text" :placeholder="disabled ? '...' : '发送消息给AI'" v-model="content" @keyup.enter="send()">
				<div class="sub_btn" @click="send()">
					<uni-icons type="paperplane-filled" color="#545454" size="25"></uni-icons>
					<!-- <uni-icons type="bars" color="#fff" size="25"></uni-icons> -->
				</div>
			</div>
		</div>

		<!-- 普通弹窗 -->
		<uni-popup ref="popup" background-color="#fff" type="left">
			<div class="popup-content" :style="'padding-top:' + menuClint.top + 'px)'">
				<button @click="startNewTalk">开始新对话</button>

				<div class="talk_list">
					<div v-for="item in talkList" @click="reTalk(item)">
						<span>{{item.data[(item.data.length - 2)].content}}</span>
						<uni-icons type="chatboxes" size="15"></uni-icons>
					</div>
				</div>

				<div class="popup_footer">
					<div style="position: relative;">
						<div class="bar" @click="toPage('/pages/reward/reward')">
							<span>打赏作者</span>
							<uni-icons type="forward" size="16"></uni-icons>
						</div>
						<div class="bar">
							<span>告诉朋友</span>
							<uni-icons type="forward" size="16"></uni-icons>
							<button data-name="shareBtn" open-type="share">告诉朋友</button>
						</div>
						<div class="bar" @click="toPage('/pages/disclaimers/disclaimers')">
							<span>免责声明</span>
							<uni-icons type="forward" size="16"></uni-icons>
						</div>
					</div>
				</div>
			</div>
		</uni-popup>
	</view>
</template>

<script>
	import Header from '@/pages/components/header'
	import contentList from '@/pages/components/content-list'
	import {
		openChat
	} from '@/api/api.js'
	import md5 from 'js-md5'
	export default {
		components: {
			Header,
			contentList
		},
		data() {
			return {
				topBar: uni.getSystemInfoSync().statusBarHeight + 10,
				// 获取菜单按钮（右上角胶囊按钮）的布局位置信息
				menuClint: uni.getMenuButtonBoundingClientRect(),
				messages: [{
					"role": "system",
					"content": "你好"
				}],
				content: "",
				disabled: false,
				dialogVisible: false,
				inputBottom: 0,
				scrollTop: 100000,
				talkList: [],
			}
		},
		created() {
			this.messages = uni.getStorageSync("messages") ? JSON.parse(uni.getStorageSync("messages")) : []
			this.talkList = uni.getStorageSync("talkList") ? JSON.parse(uni.getStorageSync("talkList")) : []
			setTimeout(_ => {
				this.handleScrollBottom() //滚动至最底部
			}, 100)
		},
		methods: {
			send() {

				this.handleScrollBottom()
				if (!this.content) {
					return
				}
				this.disabled = true
				let timeStamp = this.getTimeStamp()
				let user = {
					"role": "user",
					"content": this.content.trim()
				}
				let system = {
					"role": "assistant",
					"content": "wait"
				}
				this.messages.push(user)
				this.messages.push(system)

				let format = this.content.trim() + timeStamp
				let sign = md5(format)
				this.content = ""

				this.handleScrollBottom() //滚动至最底部

				let req = {
					messages: this.messages.slice(0, -1),
					model: "gpt-3.5-turbo",
					sign: sign,
					timestamp: timeStamp
				}

				openChat(req).then(res => {
					this.messages[(this.messages.length - 1)].content = res.data.choices[0].text
					this.handleScrollBottom() //滚动至最底部
					this.disabled = false

				}, error => {
					let system = {
						"role": "assistant",
						"content": "服务器繁忙，请重新尝试"
					}
					this.messages[(this.messages.length - 1)] = system
					this.handleScrollBottom() //滚动至最底部
					this.disabled = false
				})
			},
			getTimeStamp() {
				let dateNow = new Date()
				let nowTime = dateNow.getTime()
				return nowTime
			},
			handleScrollBottom() {
				uni.setStorageSync("messages", JSON.stringify(this.messages))

				this.$nextTick(() => {
					uni.createSelectorQuery().select("#chat_list").boundingClientRect((res) => {
						this.scrollTop = this.scrollTop + this.getTimeStamp()
					}).exec()
				})
			},
			handleClose(done) {
				done();
			},
			focusTextarea(e) {
				this.inputBottom = e.detail.height;
				this.handleScrollBottom() //滚动至最底部
			},
			blurTextarea(e) {
				this.inputBottom = 0;
				this.handleScrollBottom() //滚动至最底部
			},
			open(type) {
				this.$refs.popup.open(type)
			},
			startNewTalk(e) {
				this.saveHistory()

				this.messages = []
				uni.setStorageSync("messages", JSON.stringify([]))
				this.$refs.popup.close()
			},
			toPage(url) {
				uni.navigateTo({
					url: url
				})
			},
			assign(text) {
				this.content = text
			},
			// 保存历史数据据
			saveHistory() {
				let obj = {
					id: this.getTimeStamp(),
					data: this.messages
				}
				if (this.messages.length > 0) {
					if (uni.getStorageSync("talkId")) {
						this.talkList.map(item => {
							if (item.id == uni.getStorageSync("talkId")) {
								item.data = this.messages
							}
						})
					} else {
						this.talkList.unshift(obj)
					}
					uni.removeStorageSync("talkId")
					this.talkList = this.talkList.slice(0, 5)
					uni.setStorageSync("talkList", JSON.stringify(this.talkList))
				}
			},
			reTalk(item) {
				this.saveHistory()

				uni.setStorageSync("talkId", item.id)
				this.messages = item.data
				this.$refs.popup.close()
				this.handleScrollBottom() //滚动至最底部
			}

		}
	}
</script>

<style lang="scss" scoped>
	.content {
		position: relative;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		font-size: 14px
	}

	.panel {
		box-sizing: border-box;
		border-radius: 10px 10px 0 0;
		background: #fff;

		.tip {
			padding-left: 6px;
			border-left: 3px solid #266dfb;
			margin-left: 20px;
			font-size: 14px;
			color: #4a4a4a;
		}

		.primary_con {
			padding: 20px 10px;
			box-sizing: border-box;
			display: flex;
			justify-content: center;
			text-align: center;

			h3 {
				margin-bottom: 10px;
				color: #303030;
			}

			div {
				width: 50%;
				padding: 10px;
				box-sizing: border-box;
			}

			p {
				line-height: 35px;
				margin-top: 6px;
				background: #f7f7f8;
				border-radius: 5px;
				font-size: 13px;
				color: #4a4a4a;

				&:active {
					background: #e9e9ea;
				}
			}
		}
	}

	.con {
		min-height: 300px;
		height: calc(100% - 50px);
		overflow: scroll;
	}

	.footer {
		position: absolute;
		width: 100%;
		left: 0;
		background: #fff;

		.input_con {
			position: relative;
			width: 100%;
			height: 50px;

			// background: #f4bb1e;

			.sub_btn {
				position: absolute;
				z-index: 3;
				display: flex;
				justify-content: center;
				align-items: center;
				top: 7px;
				right: 10px;
				height: 36px;
				width: 36px;
				text-align: center;
				color: rgba(30, 30, 30, 0.6);
				cursor: pointer;
				transition: 0.2s;

				&:active {
					background: #eee;
					border-radius: 5px;
				}
			}
		}

		input {
			width: 100%;
			box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.07);
			padding-left: 10px;
			padding-right: 40px;
			box-sizing: border-box;
			line-height: 50px;
			height: 50px;

			&:focus {
				outline: none;
				border: 1px solid #f4bb1e;
				box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.03);
			}
		}
	}

	.popup-content {
		position: relative;
		height: 100vh;
		width: 60vw;
		padding-top: 100px;
		box-sizing: border-box;
		text-align: center;

		button {
			width: 80%;
			margin-left: 10%;
			background: #4684ff;
			color: #fff;
			height: 40px;
			font-size: 14px;
			line-height: 40px;
			box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.08);
			transition: 0.3s;
			margin-bottom: 10px;

			&:active {
				background: #266dfb;
			}
		}

		.talk_list {
			width: 80%;
			margin-left: 10%;
			margin-top: 10px;

			div {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 45px;
				border-bottom: 1px solid #ddd;
				padding: 0 6px 0 10px;
				font-size: 14px;
				box-sizing: border-box;

				span {
					display: inline-block;
					text-align: left;
					width: 80%;
					overflow: hidden;
					word-break: break-all;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 1;
				}

				&:active {
					background: #eee;
				}
			}
		}

		.popup_footer {
			position: absolute;
			width: 80%;
			margin-left: 10%;
			bottom: 10vw;
			border-radius: 5px;
			overflow: hidden;
			color: #303030;

			.bar {
				position: relative;
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 45px;
				border-bottom: 1px solid #ddd;
				background: #f5f5f5;
				padding: 0 6px 0 10px;
				font-size: 14px;
				box-sizing: border-box;

				&:active {
					background: #ddd;
				}

				&:nth-child(3) {
					border: none;
				}

				button {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					opacity: 0;
				}
			}
		}
	}
</style>
